<?php

/**
 *  合同mo'ban 
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 10:02
 */
namespace app\api\controller\basemanage;

use app\api\controller\common\ApiBase;
use PhpOffice\PhpWord\TemplateProcessor;
use app\api\controller\common\CommonPlus;

class Contractmodown extends ApiBase
{

    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        $this->admin = session('admin');
        $this->model = model('Contractmodown');
    }

    /**
     * 合同管理列表页
     * 模糊查询需后补 暂时先做普版
     */
    public function contractmobanList()
    {
        $keyword = $this->request->param('keyword');
        $template_type = $this->request->param('template_type');
        $project = $this->request->param('project');
        $page = $this->request->param('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 10;
        $where['a.is_delete'] = 0;

        if (!empty($keyword)) {
            $where['a.title'] = array('like', '%' . $keyword . '%');
        }
        if (!empty($template_type)) {
            $where['a.template_type'] = $template_type;
        }
        if (!empty($project)) {
            $where['a.project'] = $project;
        }

        $list =  $this->model
                ->alias('a')
                ->field('a.id,a.title,a.value,a.template_type,a.project,a.create_time,e.title as e_title,t.contract_name')
                ->join('exhibition e','a.project=e.id','left')
                ->join('contract_type t','a.template_type=t.id','left')
                ->where($where)
                ->limit(($page-1)*$pagesize.','.$pagesize)
                ->order('a.id desc')
                ->select();
         $total = $this->model
                ->alias('a')
                ->field('a.id,a.title,a.value,a.template_type,a.project,e.title,t.contract_name')
                ->join('exhibition e','a.project=e.id','left')
                ->join('contract_type t','a.template_type=t.id','left')
                ->where($where)
                ->count();
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list?$list:array(), 'total' => $total]]);
    }

    /**
     * 合同基本信息
     * 这边应该也会关联很多  后续考虑 stj 
     * @return \think\response\Json|void
     */
    public function contractDetail()
    {
        $com = new CommonPlus();
        $id = $this->request->param('id');

        $where['id'] = $id;
        //$where['is_delete'] = 0;
        $info = $this->model->findWhere($where);
     
        // 获取 D表
        $where1 = array('mid' => $id);
        $r1 = $com->sel_com_fxlist("f", $where1, "contract_detail");
        $info['D_detail'] = $r1;
        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }


    /**
     * 新增合同
     * 缺少文件转doc 
     * 具体要实现什么样的》》》
     * 2：应该还需要合同的明细表
     * 
     * @return \think\response\Json|void
     */
    public function addContract()
    {
        //==common
        $create_uid = $this->admin['id'];
        $remark = $this->request->param('remark');
        //== comon    
        $name_zs = $this->request->param('name_zs'); //展商名称:
        $addr = $this->request->param('addr');
        $tel = $this->request->param('tel');
        $fax = $this->request->param('fax');  // 传真
        $people_jinban = $this->request->param('people_jinban'); //经办人
        $type_canzhan = $this->request->param('type_canzhan'); // 参展展品类别
        $ht_id = $this->request->param('ht_id'); // 合同编号
        $ht_name = $this->request->param('ht_name'); // 合同名称
        $people_qianyue = $this->request->param('people_qianyue'); // 签约人
        $customername = $this->request->param('customername'); // 客户名称
        $ht_time = strtotime($this->request->param('ht_time')); // 合同日期
        $ht_time_endpay = strtotime($this->request->param('ht_time_endpay')); // 付款截止日期
        $money_total_xiangmu = $this->request->param('money_total_xiangmu'); // 项目总金额
        $money_zhuce = $this->request->param('money_zhuce'); // 注册费
        $money_total_ht = $this->request->param('money_total_ht'); // 合同总金额
        $pay_planname = $this->request->param('pay_planname'); // 付款计划名称
        $money_pay_one = $this->request->param('money_pay_one'); // 单笔支付
        $money_pay_total_fk = $this->request->param('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = strtotime($this->request->param('time_pay_endfk')); // 付款截至日期
        $per_fk = $this->request->param('per_fk'); // 付款比例    


        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'create_time' => time(),
            'name_zs' => $name_zs, 'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk
        );

        $r = $this->model->insertData($data);
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        // 明细 开始

        /**
         * 服务类别  下拉框 还是文本框？？？
         * sort 是永远 递增
         */
        // 测试
        $detaildata11 = array(
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "2.00", "price_sale" => "7", "discount" => "1.5", "num" => "10", "price_prate" => "2", "price_count" => "110", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "30.00", "price_sale" => "8", "discount" => "1.2", "num" => "20", "price_prate" => "3", "price_count" => "115", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "40.00", "price_sale" => "9", "discount" => "1.3", "num" => "30", "price_prate" => "5", "price_count" => "98", "remark" => "remark"),
        );
 
               //增加明细   包含更新
        $detaildata1 = $this->request->param('D_detail'); // 数组 
               // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        $detaildata = json_decode($detaildata1, TRUE);
        //$detaildata = 0;
        $z_id = $r; // 主id
        if (is_array($detaildata)) {
            $i = 0;
            foreach ($detaildata as $item) {
                $i++;
                $data_d = array(
                    'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],
                    //'type_serviceid' => $item['type_serviceid'], 
                    'type_service' => $item['type_service'], 'price' => $item['price'],
                    'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
                    'price_count' => $item['price_count'], 'remark' => $item['remark']
                );
                $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


            }
        }
        // 明细end  

        // 根据模版 转doc 2：回头在更新主表new file 
        $htmodel = $this->request->param('htmodel'); // 获取选择的合同模版   
        if(!empty($htmodel)){
            $data['htmodel'] = $htmodel;
            $data['z_id'] = $r;
            $items = $data;
             // 记录主表filepath 
            $res=$this->formbuilddoc("ff",$items);  //转 doc
        }     
      
        // 

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 也是需要编辑明细的D表  这个回头在说
     * 
     */
    public function editContract()
    {
        $id = $this->request->param('id');
        //==common
        $create_uid = $this->admin['id'];
        $remark = $this->request->param('remark');
        //== comon    
        $name_zs = $this->request->param('name_zs'); //展商名称:
        $addr = $this->request->param('addr');
        $tel = $this->request->param('tel');
        $fax = $this->request->param('fax');  // 传真
        $people_jinban = $this->request->param('people_jinban'); //经办人
        $type_canzhan = $this->request->param('type_canzhan'); // 参展展品类别
        $ht_id = $this->request->param('ht_id'); // 合同编号
        $ht_name = $this->request->param('ht_name'); // 合同名称
        $people_qianyue = $this->request->param('people_qianyue'); // 签约人
        $customername = $this->request->param('customername'); // 客户名称
        $ht_time = $this->request->param('ht_time'); // 合同日期
        $ht_time_endpay = $this->request->param('ht_time_endpay'); // 付款截止日期
        $money_total_xiangmu = $this->request->param('money_total_xiangmu'); // 项目总金额
        $money_zhuce = $this->request->param('money_zhuce'); // 注册费
        $money_total_ht = $this->request->param('money_total_ht'); // 合同总金额
        $pay_planname = $this->request->param('pay_planname'); // 付款计划名称
        $money_pay_one = $this->request->param('money_pay_one'); // 单笔支付
        $money_pay_total_fk = $this->request->param('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = $this->request->param('time_pay_endfk'); // 付款截至日期
        $per_fk = $this->request->param('per_fk'); // 付款比例    


        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'update_time' => time(),
            'name_zs' => $name_zs, 'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk
        );

        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data, $where);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        // 明细 开始

        /**
         * 服务类别  下拉框 还是文本框？？？
         * sortid  永远
         */
        // 测试
        $detaildata22 = array(
            array("pro_name" => "pro_name18988", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "2.00", "price_sale" => "7", "discount" => "1.5", "num" => "10", "price_prate" => "2", "price_count" => "110", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "30.00", "price_sale" => "8", "discount" => "1.2", "num" => "20", "price_prate" => "3", "price_count" => "115", "remark" => "remark"),
            array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "40.00", "price_sale" => "9", "discount" => "1.3", "num" => "30", "price_prate" => "5", "price_count" => "98", "remark" => "remark"),
        );
        //   var_dump($detaildata);die; 
        //增加明细   包含更新
        $detaildata1 = $this->request->param('D_detail'); // 数组 
        // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        $detaildata = json_decode($detaildata1, TRUE);
 
        // var_dump( $detaildata);die; 
        $z_id = $id; // 主id
        if (is_array($detaildata)) {
            $i = 0;
            foreach ($detaildata as $item) {
                $i++;
                $data_d = array(
                    'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],
                    //'type_serviceid' => $item['type_serviceid'], 
                    'type_service' => $item['type_service'], 'price' => $item['price'],
                    'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
                    'price_count' => $item['price_count'], 'remark' => $item['remark']
                );
                $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


            }
        }
        // 明细end  
       // 根据模版 转doc 2：回头在更新主表new file 
       $htmodel = $this->request->param('htmodel'); // 获取选择的合同模版    
       if(!empty($htmodel)){
        $data['htmodel'] = $htmodel;
        $data['z_id'] =  $id; // 编辑 id 编辑
        $items = $data;
        // 记录主表filepath 
        $res=$this->formbuilddoc("ff",$items);  //转 doc
       }    
  

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 删除项目
     * 1：列表 删除 是不是同时要删除子表。这个是大的删除
     * 2：合同主项 里面要依次删除呢？需要重写方法fsd 
     */
    public function delContract()
    {
        $id = $this->request->param('id');
        $create_uid = $this->admin['id'];

        // $where = ['id' => $id, 'create_uid' => $create_uid, 'is_delete' => 0];
        $where = ['id' => $id];
        $r = $this->model->countWhere($where);

        if (empty($r)) {
            return json(['code' => 0, 'msg' => '记录不存在，请核实']);
        }

        $r = $this->model->deleteWhere(['id' => $id]);
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }


    /**
     * 理论上要支持操作子表的更新 放一个button 在 页面的中间？？？
     * 具体怎么操作 问下   暂废弃。。防止错误操作，或者忘记提交
     * 
     */
    public function editContract_d()
    {
        $id = $this->request->param('id');
        $title = $this->request->param('title');
        $create_uid = $this->admin['id'];
        $remark = $this->request->param('remark');

        $data = array('title' => $title, 'remark' => $remark, 'update_time' => time());


        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data, $where);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 支持单独的子表操作
     * 是否在页面添加按钮 允许此操作？？
     * 赞不开启
     * 
     */
    public function delContract_d()
    {

        $mid = $this->request->param('mid');
        $sortIds = $this->request->param('sortids');
        foreach ($sortIds as $item) {
            $r = $this->model->deleteWhere_d(['sortid' => $item, 'mid' => $mid]);
        }

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }
    /**
     *  查询合同模版列表 供存档用
     * 主要  添加合同要生成模版。有新模版就继续手动编辑变量。然后 上传 追来源
     * com sel  一些基础传参
     */
    public function sel_htmode()
    {
        $com = new CommonPlus();
        $where = array('is_delete' => 0);
        $r = $com->sel_com_fxlist("f", $where, "contract_mould_yc");

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功', 'data' => $r]);
    }

    /**
     * 生成合同模版 新增调用
     * ${keti} tag
     * 替换 形成 新文件，并更新主表 存储 log
     * 前端应该下拉框与后台保持一致；
     * 
     */
    public function formbuilddoc($type, $items)
    {
        $doc = new CommonPlus();
        $Billno = $doc->createNO('HT-', 1);
        $filenewname = $Billno . '.docx';
        $comptype = "DZ";
        $comptype1 = $comptype == "MY" ? "Y" : "";
        $comptype2 = $comptype == "HZ" ? "Y" : "";
        $comptype3 = $comptype == "DZ" ? "Y" : "";
        $type = "HT";
        //$HTfile = array('modelfile' => '2019PLF-biaogaite.docx', 'newfile' => $filenewname);
        $HTfile = array('modelfile' => $items['htmodel'], 'newfile' => $filenewname);
        // 传参数过去 替换
        $params = array(
            "company_name" => $items['name_zs'], "company_name_en" => "suzhouugnagh", "company_address" => "苏州相城",
            "contact" => "张三", "link" => "www.baidu", "positions" => "科长", "email" => "184511852@qq.com",
            "tel" => "17625010777", "mobile" => "17625010778", "comptype1" => $comptype1, "comptype2" => $comptype2, "comptype3" => $comptype3
        );

        //$isfile = $doc->checkHTmodelfile($type, $HTfile['modelfile']);  // 检测

        $isfile = 2;
        if ($isfile > 0) {
            $res = $doc->dobuildDoc($type, $HTfile, $params);
            //var_dump( $res );die;
            if ($res['info']) {
                return json(['code' => 0, 'msg' => '合同生成失败']);
            }
            else {
                // return json(['code' => 1, 'msg' => '合同生成成功']);
                // 更新主表相关信息         
                $data1 = array(
                    'htmodel' => $items['htmodel'], 'model_newfile' => $res['model_newfile']
                );
                $where['id'] = $items['z_id'];
                $r = $this->model->updateBywhere($data1, $where);
            }
        }
        else {
            return json(['code' => 0, 'msg' => '合同模板不存在']);
        }
    }




    /**
     * 生成合同模版 测试用
     * ${keti} tag
     * 替换 形成 新文件，
     * 前端应该下拉框与后台保持一致；
     */
    public function builddoc()
    {
        $doc = new CommonPlus();
        $Billno = $doc->createNO('HT-', 1);
        $filenewname = $Billno . '.docx';
        $comptype = "DZ";
        $comptype1 = $comptype == "MY" ? "Y" : "";
        $comptype2 = $comptype == "HZ" ? "Y" : "";
        $comptype3 = $comptype == "DZ" ? "Y" : "";
        $type = "HT";
        $HTfile = array('modelfile' => '2019PLF-biaogaite.docx', 'newfile' => $filenewname);
        // 传参数过去 替换
        $params = array(
            "company_name" => "苏州光辉", "company_name_en" => "suzhouugnagh", "company_address" => "苏州相城",
            "contact" => "张三", "link" => "www.baidu", "positions" => "科长", "email" => "184511852@qq.com",
            "tel" => "17625010777", "mobile" => "17625010778", "comptype1" => $comptype1, "comptype2" => $comptype2, "comptype3" => $comptype3
        );

        $isfile = $doc->checkHTmodelfile($type, $HTfile['modelfile']);
        // var_dump($isfile);die;
        // $isfile=2;
        if ($isfile > 0) {
            $res = $doc->dobuildDoc($type, $HTfile, $params);
            if ($res) {
                return json(['code' => 0, 'msg' => '合同生成失败']);
            }
            else {
                return json(['code' => 1, 'msg' => '合同生成成功']);
            }
        }
        else {
            return json(['code' => 0, 'msg' => '合同模板不存在']);
        }
    }


    // the ed

    //合同模板复用展会列表
    public function projectList(){
        if (request()->isPost()) {
            $where['is_delete'] = 0;
            $list = db('exhibition')
            ->where($where)
            ->order('id desc')
            ->select();
            return json(['code'=>1,'msg'=>'success','data'=>$list?$list:array()]);
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //合同模板复用项目类型列表
    public function contractList()
    {
        if (request()->isPost()) {
            $where['is_delete']=0;
            $result = db('contract_type')->where($where)->order('id desc')->select();
            if($result){
                return json(array('code' => '1', 'msg' => '获取成功','data'=>$result?$result:array()));
            }else{
                return json(array('code' => '0', 'msg' => '获取失败'));
            }
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    //合同模板保存
    public function contractAdd()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $title = isset($post['title']) && $post['title'] != '' ? $post['title'] : null;
            $template_type = isset($post['template_type']) && $post['template_type'] != '' ? $post['template_type'] : 0;
            $value = isset($post['value']) && $post['value'] != '' ? $post['value'] : 0;
            $project = isset($post['project']) && $post['project'] != '' ? $post['project'] : 0;
            if(!$title){
                return json(array('code' => '0', 'msg' => '请填写模板名称'));
            }
            if(!$template_type){
                return json(array('code' => '0', 'msg' => '请选择合同模板类型'));
            }
            if(!$value){
                return json(array('code' => '0', 'msg' => '请上传合同模板文件'));
            }
            if(!$project){
                return json(array('code' => '0', 'msg' => '请选择合同模板所属展会'));
            }
            $data['title']=$title;
            $data['template_type']=$template_type;
            $data['value']=$value;
            $data['project']=$project;
            $result=$this->model->insertData($data);
            if($result){
                return json(array('code' => '1', 'msg' => '添加成功'));
            }else{
                return json(array('code' => '0', 'msg' => '添加失败'));
            }
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //合同模板编辑
    public function contractEdit()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
            $title = isset($post['title']) && $post['title'] != '' ? $post['title'] : null;
            $template_type = isset($post['template_type']) && $post['template_type'] != '' ? $post['template_type'] : 0;
            $value = isset($post['value']) && $post['value'] != '' ? $post['value'] : 0;
            $project = isset($post['project']) && $post['project'] != '' ? $post['project'] : 0;
            if(!$id){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }
            if(!$title){
                return json(array('code' => '0', 'msg' => '请填写模板名称'));
            }
            if(!$template_type){
                return json(array('code' => '0', 'msg' => '请选择合同模板类型'));
            }
            if(!$value){
                return json(array('code' => '0', 'msg' => '请上传合同模板文件'));
            }
            if(!$project){
                return json(array('code' => '0', 'msg' => '请选择合同模板所属展会'));
            }
            $data['title']=$title;
            $data['template_type']=$template_type;
            $data['value']=$value;
            $data['project']=$project;
            $data['create_time']=time();
            $result=$this->model->updateBywhere($data,['id'=>$id]);
            if($result){
                return json(array('code' => '1', 'msg' => '添加成功'));
            }else{
                return json(array('code' => '0', 'msg' => '添加失败'));
            }
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    //合同模板编辑删除
    public function contractDel()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
            if(!$id){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }
            $result=$this->model->deleteWhere(['id'=>$id]);
            if($result){
                return json(array('code' => '1', 'msg' => '删除成功'));
            }else{
                return json(array('code' => '0', 'msg' => '删除失败'));
            }
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


}
